<script setup lang="ts">
import { nextTick, ref, shallowRef, watch, computed } from "vue";
import { useColumns } from "./columns";
import { useEditColumns } from "./edit_table_columns";
import "plus-pro-components/es/components/search/style/css";
import { addDialog } from "@/components/ReDialog";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import Empty from "@/assets/common/empty.svg?component";
import UploadIcon from "~icons/ri/upload-2-line?width=26&height=26";
import AddFill from "~icons/ep/plus";
import Delete from "~icons/ep/delete";
import Plus from "~icons/ep/plus";
import {
  fixImageUrl,
  handleImagesUpload,
  handleImagesUploadEditor,
  imageFile
} from "@/utils/common";
import { uploadImage } from "@/api/common";
import { addMeet, setMeet, getMeetInfo } from "@/api/meeting";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { router } from "@/router";

import "@wangeditor/editor/dist/css/style.css";
defineOptions({
  name: "OperateMeeting"
});
import {
  type PlusColumn,
  type FieldValues,
  PlusDialogForm,
  PlusSearch
} from "plus-pro-components";
import {
  type Action,
  genFileId,
  ElMessageBox,
  ElMessage,
  UploadInstance,
  UploadProps,
  UploadRawFile
} from "element-plus";

import { useMenu } from "@/utils/power";
const power = useMenu(["add", "edit"]);

const mode = "default";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const toolbarConfig: any = {}; // { excludeKeys: "fullScreen" };
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      customUpload: async (file: File, insertFn) => {
        try {
          const res = await handleImagesUploadEditor(file);
          insertFn(res.data, "", res.data);
        } catch (error) {
          console.error(error);
        }
      }
    },
    insertVideo: {
      onInsertedVideo: async video => {
        if (video == null) return;
      }
    },
    uploadVideo: {
      customUpload: async (file: File, insertFn) => {
        try {
          const res = await handleImagesUploadEditor(file);
          insertFn(res.data, "");
        } catch (error) {
          console.error(error);
        }
      }
    }
  }
};
const handleCreated = editor => {
  // 记录 editor 实例，重要！
  editorRef.value = editor;
};

const tableRef = ref();
const searchValues = ref({
  actType: 2
});
const defaultSearchState = ref({
  actType: 2
});

const { editColumns, couponColumns, deleteCouponFunc } = useEditColumns();

const searchColumns: PlusColumn[] = [
  {
    label: "搜索",
    width: 100,
    prop: "keyWord",
    valueType: "copy",
    tooltip: "请输入搜索关键词"
  },
  {
    label: "旅游状态",
    width: 200,
    labelWidth: 100,
    prop: "status",
    valueType: "select",
    tooltip: "请选择旅游状态",
    options: [
      {
        label: "全部",
        value: 0,
        color: "red"
      },
      {
        label: "进行中",
        value: 1,
        color: "red"
      }
    ]
  }
];

const rules = {
  title: [
    {
      required: false,
      message: "新闻标题必填"
    }
  ],
  banner: [
    {
      required: false,
      message: "新闻封面必填"
    }
  ],
  content: [
    {
      required: false,
      message: "新闻内容必填"
    }
  ]
};
const previewImageUrl = ref();
const previewImageName = ref();
const showPreviewImage = ref(false);

const bannerImageRef = ref<UploadInstance>();
const edit = ref(false);
const confirmLoading = ref(false);
const visible = ref(false);
const values = ref({});
const hideSingleControl = computed(() => values.value.controlType === 1);
const formRef = ref();
const formColumns: PlusColumn[] = [
  {
    label: "旅游名称",
    prop: "meetingTitle",
    valueType: "input",
    tooltip: "请输入旅游名称"
  },
  {
    label: "主办单位",
    prop: "company",
    valueType: "input",
    tooltip: "请输入主办单位"
  },
  {
    label: "旅游描述",
    prop: "about",
    valueType: "textarea"
  },
  {
    label: "售票开始时间",
    prop: "startTime",
    width: 120,
    valueType: "date-picker",
    fieldProps: {
      type: "datetime",
      format: "YYYY-MM-DD HH:mm:ss",
      "value-format": "YYYY-MM-DD HH:mm:ss"
    },
    tooltip: "请输入旅游开始时间"
  },
  {
    label: "售票结束时间",
    width: 120,
    prop: "endTime",
    valueType: "date-picker",
    fieldProps: {
      type: "datetime",
      format: "YYYY-MM-DD HH:mm:ss",
      "value-format": "YYYY-MM-DD HH:mm:ss"
    },
    tooltip: "请输入旅游结束时间"
  },
  {
    label: "展示开始时间",
    prop: "showStartTime",
    width: 120,
    valueType: "date-picker",
    fieldProps: {
      type: "datetime",
      format: "YYYY-MM-DD HH:mm:ss",
      "value-format": "YYYY-MM-DD HH:mm:ss"
    }
  },
  {
    label: "展示结束时间",
    prop: "showEndTime",
    width: 120,
    valueType: "date-picker",
    fieldProps: {
      type: "datetime",
      format: "YYYY-MM-DD HH:mm:ss",
      "value-format": "YYYY-MM-DD HH:mm:ss"
    }
  },
  {
    label: "旅游时间描述",
    prop: "timeDesc",
    valueType: "input"
  },
  {
    label: "旅游封面",
    prop: "banner",
    valueType: "img",
    tooltip: "请输入封面图片地址"
  },
  {
    label: "介绍图片",
    width: 120,
    prop: "imgs",
    valueType: "img",
    tooltip: "上传旅游介绍图片"
  },
  {
    label: "价格区间",
    prop: "pricePoint",
    valueType: "input"
  },
  {
    label: "支付方式",
    prop: "payType",
    valueType: "checkbox",
    options: [
      {
        label: "余额",
        value: 0
      },
      {
        label: "收益",
        value: 1
      },
      {
        label: "积分",
        value: 2
      },
      {
        label: "消费券",
        value: 3
      }
    ]
  },
  {
    label: "旅游地址",
    prop: "address",
    valueType: "input"
  },
  {
    label: "经度",
    prop: "longitude",
    valueType: "input"
  },
  {
    label: "纬度",
    prop: "latitude",
    valueType: "input"
  },
  {
    label: "联系电话",
    prop: "call",
    valueType: "input"
  },
  {
    label: "人员控制",
    prop: "controlType",
    valueType: "radio",
    options: [
      {
        label: "活动控制",
        value: 0,
        color: "red"
      },
      {
        label: "券本身进行控制",
        value: 1,
        color: "red"
      }
    ]
  },
  {
    label: "活动总人数",
    prop: "totalNum",
    valueType: "input-number",
    tooltip: "-1表示不限制",
    hideInForm: hideSingleControl,
    fieldProps: { precision: 0, step: 100 }
  },
  {
    label: "剩余人数",
    prop: "leftNum",
    valueType: "input-number",
    hideInForm: hideSingleControl,
    fieldProps: { precision: 0, step: 100 }
  },
  {
    label: "最多可领取数量",
    prop: "maxNum",
    valueType: "input-number",
    hideInForm: hideSingleControl,
    fieldProps: { precision: 0, step: 1 }
  },
  {
    label: "旅游详情",
    prop: "details"
  },
  {
    label: "报名列表",
    prop: "joinUser"
  },
  {
    label: "场次列表",
    prop: "coupon"
  },
  {
    label: "是否删除",
    width: 100,
    prop: "isDelete",
    valueType: "switch",
    fieldProps: {
      activeValue: 1,
      inactiveValue: 0
    }
  }
];

watch(
  () => values.value.controlType,
  newVal => {
    console.log("controlType changed to:", newVal);
    // 根据不同的控制类型执行不同逻辑
    if (newVal === 0) {
      // 活动控制时的处理
      console.log("活动控制模式");
    } else if (newVal === 1) {
      // 券本身控制的处理
      console.log("券本身控制模式");
      values.value.totalNum = -1;
      values.value.leftNum = -1;
      values.value.maxNum = -1;
    }
  }
);

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  loadData,
  onSizeChange,
  onKeywordChange,
  onCurrentChange
} = useColumns();

const columnsRef = computed(() => {
  if (power.value.edit) {
    return columns;
  }
  const columnsCopy = [...columns];
  return columnsCopy.slice(0, -1);
});

const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset");
  onKeywordChange(value);
};

const handleChange = (value: any, target: any) => {
  console.log("change", value);
  if (target.prop == "keyWord") {
    return;
  }
  onKeywordChange(value);
};

const editClick = async row => {
  console.log(
    "%crow===详情>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  try {
    const res = await getMeetInfo(row.mId);
    const data = res.data;
    data.coupon = data.coupon.map(item => {
      item.isDelete = 0;
      return item;
    });
    values.value = data;
    edit.value = true;
    visible.value = true;
  } catch (error) {
    console.error(error);
  }
};
const add = () => {
  edit.value = false;
  values.value = {
    actType: 2,
    coupon: [],
    joinUser: [
      {
        key: "u_name",
        type: "text",
        title: "用户姓名",
        value: "",
        required: "true"
      },
      {
        key: "u_mobile",
        type: "text",
        title: "联系方式",
        value: "",
        required: "true"
      },
      {
        key: "u_address",
        type: "text",
        title: "联系地址",
        value: "",
        required: "true"
      }
    ]
  };

  visible.value = true;
};
const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...values.value };
  const newContent = updatedValues.details.replace(
    /width="(?:auto|\d+)"/g,
    'width="100%"'
  );
  updatedValues.details = newContent;
  updatedValues.joinUser = JSON.stringify(updatedValues.joinUser);
  confirmLoading.value = true;
  if (hideSingleControl.value) {
    updatedValues.totalNum = -1;
    updatedValues.leftNum = -1;
    updatedValues.maxNum = -1;
  }
  if (edit.value) {
    try {
      await setMeet(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  } else {
    try {
      await addMeet(updatedValues);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      editorRef.value?.clear();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  }
};
const handleCancel = () => {
  console.log("取消");
  editorRef.value?.clear();
};
const handleBannerImageSuccess: UploadProps["onSuccess"] = (res, file) => {
  values.value.banner = res.data;
};
const handleBannerImageRemove: UploadProps["onRemove"] = (file, files) => {
  values.value.banner = undefined;
  console.log(
    "%cfile===>>>",
    "color: MidnightBlue; font-size: 20px;",
    file,
    files
  );
};
/// 超出limit限制 先清空文件列表再执行上传
const handleBannerImageExceed: UploadProps["onExceed"] = files => {
  bannerImageRef.value?.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  bannerImageRef.value?.handleStart(file);
  bannerImageRef.value?.submit();
};

const handleImagesSuccess: UploadProps["onSuccess"] = (res, file) => {
  console.log(
    "%cfile===>>>",
    "color: MidnightBlue; font-size: 20px;",
    file,
    res
  );
  if (res.code != 0) {
    ElMessage.error(res.msg);
    return;
  }
  const image = res.data;
  if (!values.value.imgs || values.value.imgs.length == 0) {
    values.value.imgs = image;
  } else {
    values.value.imgs += `,${image}`;
  }
};
const handleImagesRemove: UploadProps["onRemove"] = (file, files) => {
  values.value.imgs = files.map(item => item.url).join(",");
  console.log("imagesRemove", values.value.images, file, files);
};
/// 超出limit限制 先清空文件列表再执行上传
const handleImagesExceed: UploadProps["onExceed"] = files => {
  ElMessage.error("最多上传5张图片");
  // productImageRef.value?.clearFiles();
  // const file = files[0] as UploadRawFile;
  // file.uid = genFileId();
  // productImageRef.value?.handleStart(file);
  // productImageRef.value?.submit();
};
const handlePreviewImage: UploadProps["onPreview"] = file => {
  previewImageName.value = file.name;
  previewImageUrl.value = file.url;
  showPreviewImage.value = true;
};

const imageList = computed(() => {
  const images = values.value.imgs as string;
  if (images && images.length > 0) {
    return imageFile(images);
  }
  return [];
});
const editTableRef = ref();
const onAdd = () => {
  if (!values.value.joinUser) {
    values.value.joinUser = [];
  }
  values.value.joinUser.push({
    key: "",
    type: "text",
    title: "",
    value: "",
    required: "false"
  });
};
const onDel = row => {
  const index = values.value.joinUser.indexOf(row);
  if (index !== -1) values.value.joinUser.splice(index, 1);
};

const onAddCoupon = () => {
  if (!values.value.coupon) {
    values.value.coupon = [];
  }
  values.value.coupon.push({
    isRefund: 1,
    isShow: 1,
    dateType: "a"
  });
};
const onDelCoupon = row => {
  const index = values.value.coupon.indexOf(row);
  if (index !== -1) values.value.coupon.splice(index, 1);
};

deleteCouponFunc.value = async row => {
  const index = values.value.coupon.indexOf(row);
  if (index !== -1) values.value.coupon.splice(index, 1);
};

const buyListClick = row => {
  console.log(row);
  router.push({ name: "OperateTourBuy", query: { id: row.mId } });
};
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>区域旅游</h3>
        </template>
        <template v-if="power.add" #extra>
          <div class="flex flex-row items-end justify-end">
            <el-button type="primary" @click="add">
              <el-icon :size="15" color="#fff">
                <IconifyIconOffline :icon="Plus" />
              </el-icon>
              添加旅游
            </el-button>
          </div>
        </template>
        <PlusSearch
          v-model="searchValues"
          :defaultValues="defaultSearchState"
          class="mt-5"
          :columns="searchColumns"
          @reset="handleReset"
          @search="handleSearch"
          @change="handleChange"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :fit="true"
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columnsRef"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #operation="{ row }">
        <el-button
          v-if="power.edit"
          type="primary"
          size="small"
          @click="editClick(row)"
        >
          编辑
        </el-button>
        <el-button
          v-if="power.edit"
          type="primary"
          size="small"
          @click="buyListClick(row)"
        >
          报名管理
        </el-button>
      </template>

      <template #banner="{ row, index }">
        <el-image
          preview-teleported
          loading="lazy"
          :src="row.banner"
          :preview-src-list="dataList.map(v => v.banner)"
          :initial-index="index"
          fit="cover"
          class="w-[50px] h-[50px]"
        />
      </template>
      <template #imgs="{ row }">
        <div class="flex flex-row flex-wrap gap-2">
          <el-image
            v-for="item in row.imgs.split(',')"
            :key="item.id"
            preview-teleported
            loading="lazy"
            :src="item"
            :preview-src-list="row.imgs.split(',')"
            fit="cover"
            class="w-[50px] h-[50px]"
          />
        </div>
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading, width: '92%' }"
      :title="edit ? '编辑旅游' : '添加旅游'"
      @confirm="handleSubmit"
      @cancel="handleCancel"
    >
      <template #plus-field-banner>
        <el-upload
          ref="bannerImageRef"
          drag
          :auto-upload="true"
          list-type="picture-card"
          :limit="1"
          :http-request="handleImagesUpload"
          :file-list="
            values.banner && values.banner.length > 0
              ? imageFile(values.banner)
              : []
          "
          :on-success="handleBannerImageSuccess"
          :on-remove="handleBannerImageRemove"
          :on-preview="handlePreviewImage"
          :on-exceed="handleBannerImageExceed"
        >
          <div>
            <UploadIcon class="m-auto mb-2" />
            可点击或拖拽上传
          </div>
        </el-upload>
      </template>
      <template #plus-field-imgs>
        <el-upload
          ref="productJSImageRef"
          drag
          :auto-upload="true"
          list-type="picture-card"
          :limit="5"
          :http-request="handleImagesUpload"
          :file-list="imageList"
          :on-success="handleImagesSuccess"
          :on-remove="handleImagesRemove"
          :on-preview="handlePreviewImage"
          :on-exceed="handleImagesExceed"
        >
          <div>
            <UploadIcon class="m-auto mb-2" />
            可点击或拖拽上传
          </div>
        </el-upload>
      </template>
      <template #plus-field-details>
        <div class="wangeditor">
          <Toolbar
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
            style="border-bottom: 1px solid #ccc"
          />
          <Editor
            v-model="values.details"
            :defaultConfig="editorConfig"
            :mode="mode"
            style="height: 500px; overflow-y: hidden"
            @onCreated="handleCreated"
          />
        </div>
      </template>
      <template #plus-field-joinUser>
        <pure-table
          ref="editTableRef"
          border
          row-key="id"
          align-whole="center"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          :data="values.joinUser"
          :columns="editColumns"
        >
          <template #empty>
            <Empty fill="var(--el-svg-monochrome-grey)" class="m-auto" />
          </template>
          <template #append>
            <el-button
              type="success"
              class="w-full my-2!"
              :icon="useRenderIcon(AddFill)"
              @click="onAdd"
            >
              添加一行数据
            </el-button>
          </template>
          <template #operation="{ row }">
            <div
              v-if="row.id && row.id > 0"
              class="flex flex-row gap-2 items-center"
            >
              是否删除<el-switch
                v-model="row.isDelete"
                :active-value="1"
                :inactive-value="0"
              />
            </div>
            <el-button
              v-else
              class="reset-margin"
              link
              type="primary"
              :icon="useRenderIcon(Delete)"
              @click="onDel(row)"
            />
          </template>
        </pure-table>
      </template>
      <template #plus-field-coupon>
        <pure-table
          border
          row-key="id"
          align-whole="center"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          :data="values.coupon"
          :columns="couponColumns"
        >
          <template #empty>
            <Empty fill="var(--el-svg-monochrome-grey)" class="m-auto" />
          </template>
          <template #append>
            <el-button
              type="success"
              class="w-full my-2!"
              :icon="useRenderIcon(AddFill)"
              @click="onAddCoupon"
            >
              添加一行数据
            </el-button>
          </template>
          <template #operation="{ row }">
            <div
              v-if="row.metId && row.metId > 0"
              class="flex flex-row gap-2 items-center"
            >
              是否删除<el-switch
                v-model="row.isDelete"
                :active-value="1"
                :inactive-value="0"
              />
            </div>
            <el-button
              v-else
              class="reset-margin"
              link
              type="primary"
              :icon="useRenderIcon(Delete)"
              @click="onDelCoupon(row)"
            />
          </template>
        </pure-table>
      </template>
    </PlusDialogForm>
    <el-dialog v-model="showPreviewImage">
      <img w-full :src="previewImageUrl" :alt="previewImageName" />
    </el-dialog>
  </ElCard>
</template>

<style scoped>
:deep(.el-descriptions),
:deep(.el-descriptions__table tr) {
  --el-card-bg-color: transparent !important;
  --el-fill-color-blank: transparent !important;
  background: transparent !important;
}
.wrap-text {
  white-space: normal !important; /* 允许自动换行 */
  word-break: break-all; /* 强制换行 */
}
:deep(video) {
  width: 100% !important;
}
:deep(.el-date-editor) {
  --el-date-editor-width: 180px !important;
}
</style>
